package com.ruoyi.delivery.utils;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Map;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

@Component
public class OpenidUtils {

    // 硬编码配置（建议生产环境改为配置）
    private static final String APP_ID = "wx7943bf38a77ddadb";
    private static final String APP_SECRET = "d2e3c47c9bc19915d985883a5652f0a6";

    public String getOpenid(String code) {
        String url = String.format(
                "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                APP_ID, APP_SECRET, code
        );

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .GET()
                .build();

        try {
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            String result = response.body();

            // 安全地解析JSON（解决未经检查的警告）
            ObjectMapper mapper = new ObjectMapper();
            Map<String, Object> data = mapper.readValue(
                    result,
                    new TypeReference<Map<String, Object>>() {
                    }
            );

            return (String) data.get("openid");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}